import configparser
import os

class Config:

    def __init__(self) -> None:
        self.config = configparser.ConfigParser()
        
        self.home_dir           = os.path.expanduser('~')
        self.config_dir_path    = self.home_dir         + "/.config/rosemary/"
        self.cache_dir_path     = self.config_dir_path  + "cache"
        self.subs_path          = self.cache_dir_path   + "/subscribes.txt"
        self.config_path        = self.config_dir_path  + "config.ini"
        self.user_plugs_path    = self.config_dir_path  + "/plugins"

        self.make_config_dir()
        self.make_plugs_dir()
        self.make_cache_dir()
        self.load_from_file()

        if not self.is_subs_exists(): 
            fp = open(self.subs_path, 'w'); fp.close()

    def is_config_exists(self) -> bool:
        return os.path.exists(self.config_path)

    def is_subs_exists(self) -> bool:
        return os.path.exists(self.subs_path)

    def make_config_dir(self) -> None:
        os.makedirs(self.config_dir_path, exist_ok=True)

    def make_plugs_dir(self) -> None:
        os.makedirs(self.user_plugs_path, exist_ok=True)

    def make_cache_dir(self) -> None:
        os.makedirs(self.cache_dir_path, exist_ok=True)

    def make_std_config(self) -> None:
        self.config.add_section('Options')
        self.config.set('Options', 'port', '5000')

    def write_to_file(self) -> None:
        with open(self.config_path, 'w') as configfile:
            self.config.write(configfile)

    def load_from_file(self) -> None:
        if not self.is_config_exists(): 
            self.make_std_config()
            return self.write_to_file() 
        self.config.read(self.config_path)

    def get_option(self, section: str, option: str) -> str:
        return self.config.get(section, option)

    def get_std_option(self, option: str) -> str:
        return self.config.get('Options', option)

    def set_option(self, section: str, option: str, value: str, rewrite: bool=False) -> None:
        if rewrite or not self.config.has_option(section, option):
            if not self.config.has_section(section): 
                self.config.add_section(section)
            self.config.set(section, option, value)
            self.write_to_file()


if __name__ == "__main__":
    cfg = Config()

